package com.swx.identityservice.webapis;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.swx.identityservice.dtos.dept.DeptListOutputDto;
import com.swx.identityservice.dtos.dept.DeptTreeDto;
import com.swx.identityservice.dtos.dept.InsertDeptInputDto;
import com.swx.identityservice.dtos.dept.UpdateDeptInputDto;
import com.swx.identityservice.dtos.role.RoleOutputDto;
import com.swx.identityservice.models.ScbpDept;
import com.swx.identityservice.models.ScbpDeptTree;
import com.swx.identityservice.service.LoginUser;
import com.swx.identityservice.service.ScbpDeptService;
import com.swx.identityservice.service.ScbpRoleService;
import com.swx.identityservice.service.ScbpUserService;
import com.swx.identityservice.utils.JaxrsResponse;
import com.swx.identityservice.utils.ResponseMessages;
import com.swx.identityservice.utils.UserUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.modelmapper.ModelMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.*;

/**
 * Created by SCBP
 */
@RestController
@Slf4j
@Api(tags = "部门控制器")
public class ScbpDeptController {

    @Autowired
    private ScbpDeptService scbpDeptService;
    private ModelMapper modelMapper;
    @Autowired
    private ScbpUserService scbpUserService;
    @Autowired
    private ScbpRoleService scbpRoleService;

    public ScbpDeptController() {
        modelMapper = new ModelMapper();
    }

    @ApiOperation("获取组织机构树形数据")
    @GetMapping(value = "/getdeptsastree")
    public List<ScbpDeptTree> getDeptsAsTree() throws Exception {
        return scbpDeptService.getDeptsAsTree(0);
    }

    @ApiOperation("获取组织机构和角色树形")
    @GetMapping(value = "/getDeptsAndRolesAsTree")
    public List<ScbpDeptTree> getDeptsAndRolesAsTree() throws Exception {
        return  scbpDeptService.getDeptsAndRolesAsTree(0);

    }

    @ApiOperation("新增部门")
    @PreAuthorize("hasAuthority('Depts_Insert')")
    @PostMapping(value = "/adddept")
    public JaxrsResponse post(@RequestBody  @Valid InsertDeptInputDto insertDeptInputDto) {
        String str = "";
        String strMapping = "";
        ScbpDept scbpDept = modelMapper.map(insertDeptInputDto, ScbpDept.class);
        Integer[] handleBusiness = insertDeptInputDto.getHandleBusiness();
        Integer[] statisticaldeptmapping = insertDeptInputDto.getStatisticaldeptmapping();
        if (handleBusiness.length <= 0 || statisticaldeptmapping.length <= 0)
            return JaxrsResponse.builder().message(ResponseMessages.INSERT_NOT_COMPLETE).build();
        for (int i = 0; i < handleBusiness.length; i++) {
            str += handleBusiness[i] + ",";
        }
        for (int i = 0; i < statisticaldeptmapping.length; i++) {
            strMapping += statisticaldeptmapping[i] + ",";
        }
        String substring = str.substring(0, str.length() - 1);
        String substringMapping = strMapping.substring(0, strMapping.length() - 1);
        scbpDept.setCreationtime(new Date());
        scbpDept.setIsdeleted(false);
        scbpDept.setHandleBusiness(substring);
        scbpDept.setStatisticaldeptmapping(substringMapping);
        LoginUser loginUser = UserUtil.getLoginUser();
        scbpDept.setCreatoruserid(loginUser.getId());
        int sr = scbpDeptService.insert(scbpDept);
        if (sr > 0) return JaxrsResponse.builder().code(0).status("success").data(scbpDept.getId()).build();
        return JaxrsResponse.builder().code(1).status("fail").message(ResponseMessages.INSERT_FAIL).build();
    }

    String result = "";
    //递归查询
    public String getTopName(int id) {
        ScbpDept scbpDept = scbpDeptService.selectDeptById(id);
        if (scbpDept.getPid() != 0) {//这就是出口
            Integer pid = scbpDept.getPid();
            return getTopName(pid);
        } else {
            result =   scbpDept.getTitle();
            return result;
        }
    }

    @ApiOperation("编辑部门")
    @PreAuthorize("hasAuthority('Depts_Edit')")
    @PostMapping(value = "/editdept")
    public JaxrsResponse put(@RequestBody @Valid UpdateDeptInputDto updateDeptInputDto) {
        String str = "";
        String strMapping = "";
        ScbpDept scbpDept = modelMapper.map(updateDeptInputDto, ScbpDept.class);
        Integer[] handleBusiness = updateDeptInputDto.getHandleBusiness();
        Integer[] statisticaldeptmapping = updateDeptInputDto.getStatisticaldeptmapping();
        for (int i = 0; i < handleBusiness.length; i++) {
            str += handleBusiness[i] + ",";
        }
        for (int i = 0; i < statisticaldeptmapping.length; i++) {
            strMapping += statisticaldeptmapping[i] + ",";
        }
        String substring = str.substring(0, str.length() - 1);
        String substringMapping = strMapping.substring(0, strMapping.length() - 1);
        scbpDept.setLastmodificationtime(new Date());
        scbpDept.setHandleBusiness(substring);
        scbpDept.setStatisticaldeptmapping(substringMapping);
        LoginUser loginUser = UserUtil.getLoginUser();
        scbpDept.setLastmodifieruserid(loginUser.getId());
        int sr = scbpDeptService.updateByPrimaryKeySelective(scbpDept);
        if (sr > 0) return JaxrsResponse.builder().code(0).status("success").data(updateDeptInputDto.getId()).build();
        return JaxrsResponse.builder().code(1).status("fail").message(ResponseMessages.UPDATE_FAIL).build();
    }

    @ApiOperation("删除部门")
    @PreAuthorize("hasAuthority('Depts_Delete')")
    @DeleteMapping(value = "/deldept")
    @ApiImplicitParams({
        @ApiImplicitParam(paramType = "query", dataType = "int", name = "deptId", value = "部门id", required = true)
    })
    public JaxrsResponse delete(@RequestParam int deptId) {
        ScbpDept dept = new ScbpDept();
        int userCount = scbpUserService.selectCountByDeptId(deptId);
        int roleCount = scbpRoleService.selectCountByDeptId(deptId);
        if (roleCount > 0) return JaxrsResponse.builder().message("删除部门前,请先删除部门下的角色").build();
        if (userCount > 0) return JaxrsResponse.builder().message("删除部门前,请先删除部门下的人员").build();
        dept.setId(deptId);
        dept.setIsdeleted(true);
        dept.setDeletiontime(new Date());
        LoginUser loginUser = UserUtil.getLoginUser();
        dept.setDeleteruserid(loginUser.getId());
        int sr = scbpDeptService.updateByPrimaryKeySelective(dept);
        if (sr > 0) return JaxrsResponse.builder().code(0).status("success").data(dept.getId()).build();
        return JaxrsResponse.builder().code(1).status("fail").message(ResponseMessages.DELETE_FAIL).build();
    }
    @ApiOperation("根据父id查询下属子节点所有信息")
    @PreAuthorize("hasAuthority('Depts_Select')")
    @GetMapping(value = "/selectdeptsbypid")
    public JaxrsResponse selectDeptsByPid(@RequestParam(defaultValue = "0", value = "Pid") int Pid,
                                          @RequestParam(defaultValue = "1", value = "pageIndex") int pageIndex,
                                          @RequestParam(defaultValue = "10", value = "pageSize") int pageSize) {
        PageHelper.startPage(pageIndex, pageSize);
        List<ScbpDept> scbpDepts = scbpDeptService.selectDeptsByPid(Pid);
        PageInfo<ScbpDept> pageInfo = new PageInfo<>(scbpDepts);
        DeptListOutputDto deptListOutputDto = new DeptListOutputDto();
        deptListOutputDto.setTotal(pageInfo.getTotal());
        Integer[] integers = null;
        Integer[] splitMappings = null;
        List<ScbpDept> scbpDepts1 = scbpDeptService.selectDeptsByPid(Pid);
        for (int i = 0; i < scbpDepts1.size(); i++) {
            String handleBusiness = scbpDepts1.get(i).getHandleBusiness();
            String statisticaldeptmapping = scbpDepts1.get(i).getStatisticaldeptmapping();
            String[] split = handleBusiness.split(",");
            String[] splitMapping = statisticaldeptmapping.split(",");
            //存放business
            integers = new Integer[split.length];
            for (int j = 0; j < split.length; j++) {
                integers[j] = Integer.parseInt(split[j]);
            }
            //存放mapping部门映射
            splitMappings = new Integer[splitMapping.length];
            for (int j = 0; j < splitMapping.length; j++) {
                splitMappings[j] = Integer.parseInt(splitMapping[j]);
            }
        }
        for (int l = 0; l < pageInfo.getList().size(); l++) {
            DeptTreeDto deptListOutputDto1 = modelMapper.map(scbpDepts.get(l), DeptTreeDto.class);
            deptListOutputDto1.setHandleBusiness(integers);
            deptListOutputDto1.setStatisticaldeptmapping(splitMappings);
            deptListOutputDto.addUser(deptListOutputDto1);
        }
        return JaxrsResponse.builder().code(0).status("success").data(deptListOutputDto).build();
    }


    @ApiOperation("查询所有部门列表")
    @GetMapping(value = "/selectdeptslist")
    public List<ScbpDept> selectDeptsList() {
        return scbpDeptService.selectDeptsList();
    }

    @ApiOperation("新增审核角色时候选择所有的顶级单位列表")

    @GetMapping(value = "/selectunit")
    public  JaxrsResponse  selectunit() {
        List<ScbpDept> scbpDepts = scbpDeptService.selectUnit();
        return JaxrsResponse.builder().status("success").data(scbpDepts).build();
    }
    @ApiOperation("新增人员的时候单位多选，然后选择角色就调用这个接口，查询出选择部门集合下的所有角色")
    @GetMapping(value = "/getrolesbydeptid")
    public JaxrsResponse getrolesbydeptid(@RequestParam("id[]") Integer[] id) {
        List<RoleOutputDto> roleOutputDtos = scbpRoleService.selectRolesByDeptId(id);
        List<Map<String, Object>> mapList = new ArrayList<>();
        Map<String, Object> map;
        for (int i = 0; i < roleOutputDtos.size(); i++) {
            map = new HashMap<>();
            Integer id1 = roleOutputDtos.get(i).getId();
            Integer did = roleOutputDtos.get(i).getDid();
            String name1 = roleOutputDtos.get(i).getName();
            String topName = getTopName(did);
            map.put("id", id1);
            map.put("name", topName + "/"+ name1);
            mapList.add(map);
        }
        return JaxrsResponse.builder().code(0).status("success").data(mapList).build();
    }
}



